<?php

namespace App\Http\Controllers\Api;

use App\Models\WorkUser;
use App\Traits\ApiResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;

/**
 * @OA\Tag(
 *     name="维护人员认证",
 *     description="维护人员登录注册相关接口"
 * )
 */
class WorkUserAuthController extends Controller
{
    use ApiResponse;

    /**
     * @OA\Post(
     *     path="/api/work-user/login",
     *     summary="维护人员登录",
     *     description="使用账号密码登录",
     *     tags={"维护人员认证"},
     *     @OA\RequestBody(
     *         required=true,
     *         @OA\JsonContent(
     *             @OA\Property(property="username", type="string", description="用户名", example="lifu"),
     *             @OA\Property(property="password", type="string", description="密码", example="123456")
     *         )
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="登录成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="success"),
     *             @OA\Property(property="code", type="integer", example=200),
     *             @OA\Property(property="data", type="object",
     *                 @OA\Property(property="token", type="string", description="认证令牌", example="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..."),
     *                 @OA\Property(property="expired_at", type="string", format="date-time", description="过期时间", example="2025-12-31 23:59:59"),
     *                 @OA\Property(property="work_user", type="object", ref="#/components/schemas/WorkUserResource")
     *             ),
     *             @OA\Property(property="message", type="string", example="登录成功")
     *         )
     *     ),
     *     @OA\Response(
     *         response=400,
     *         description="参数校验失败",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="failed"),
     *             @OA\Property(property="code", type="integer", example=400),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="参数校验失败")
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="登录失败",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="failed"),
     *             @OA\Property(property="code", type="integer", example=401),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="用户名或密码错误")
     *         )
     *     ),
     *     @OA\Response(
     *         response=500,
     *         description="服务器错误",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="error"),
     *             @OA\Property(property="code", type="integer", example=500),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="服务器内部错误")
     *         )
     *     )
     * )
     */
    public function login(Request $request)
    {
        try {
            $validated = $request->validate([
                'username' => ['required', 'string', 'max:255'],
                'password' => ['required', 'string', 'min:6', 'max:255'],
            ], [
                'username.required' => '用户名不能为空',
                'username.string' => '用户名必须是字符串',
                'username.max' => '用户名不能超过255个字符',
                'password.required' => '密码不能为空',
                'password.string' => '密码必须是字符串',
                'password.min' => '密码不能少于6个字符',
                'password.max' => '密码不能超过255个字符',
            ]);

            $workUser = WorkUser::where(WorkUser::USERNAME, $validated['username'])
                ->where(WorkUser::ENABLE, true)
                ->first();

            if (!$workUser || !Hash::check($validated['password'], $workUser->password)) {
                return $this->failed('用户名或密码错误', 401);
            }

            // 生成新的token和过期时间
            $token = md5(uniqid() . time() . $workUser->id);
            $expiredAt = now()->addDays(30); // 30天过期

            $workUser->token = $token;
            $workUser->expired_at = $expiredAt;
            $workUser->save();

            return $this->success([
                'token' => $token,
                'expired_at' => $expiredAt->toDateTimeString(),
                'work_user' => new \App\Http\Resources\WorkUserResource($workUser)
            ], '登录成功');

        } catch (ValidationException $e) {
            return $this->failed($e->getMessage());
        } catch (\Exception $e) {
            return $this->error('登录失败');
        }
    }

    /**
     * @OA\Post(
     *     path="/api/work-user/register",
     *     summary="维护人员注册",
     *     description="注册新的维护人员账号",
     *     tags={"维护人员认证"},
     *     @OA\RequestBody(
     *         required=true,
     *         @OA\JsonContent(
     *             @OA\Property(property="real_name", type="string", description="真实姓名", example="李师傅"),
     *             @OA\Property(property="username", type="string", description="用户名", example="lifu"),
     *             @OA\Property(property="password", type="string", description="密码", example="123456"),
     *             @OA\Property(property="password_confirmation", type="string", description="确认密码", example="123456"),
     *             @OA\Property(property="tel", type="string", description="联系电话", example="13800138000"),
     *             @OA\Property(property="memo", type="string", description="备注", example="电工师傅")
     *         )
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="注册成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="success"),
     *             @OA\Property(property="code", type="integer", example=200),
     *             @OA\Property(property="data", type="object",
     *                 @OA\Property(property="token", type="string", description="认证令牌", example="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..."),
     *                 @OA\Property(property="expired_at", type="string", format="date-time", description="过期时间", example="2025-12-31 23:59:59"),
     *                 @OA\Property(property="work_user", type="object", ref="#/components/schemas/WorkUserResource")
     *             ),
     *             @OA\Property(property="message", type="string", example="注册成功")
     *         )
     *     ),
     *     @OA\Response(
     *         response=400,
     *         description="参数校验失败",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="failed"),
     *             @OA\Property(property="code", type="integer", example=400),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="参数校验失败")
     *         )
     *     ),
     *     @OA\Response(
     *         response=409,
     *         description="用户名已存在",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="failed"),
     *             @OA\Property(property="code", type="integer", example=409),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="用户名已存在")
     *         )
     *     ),
     *     @OA\Response(
     *         response=500,
     *         description="服务器错误",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="error"),
     *             @OA\Property(property="code", type="integer", example=500),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="服务器内部错误")
     *         )
     *     )
     * )
     */
    public function register(Request $request)
    {
        try {
            $validated = $request->validate([
                'real_name' => ['required', 'string', 'max:255'],
                'username' => ['required', 'string', 'max:255', 'unique:work_users,username'],
                'password' => ['required', 'string', 'min:6', 'max:255', 'confirmed'],
                'tel' => ['sometimes', 'nullable', 'string', 'max:20'],
                'memo' => ['sometimes', 'nullable', 'string', 'max:500'],
            ], [
                'real_name.required' => '真实姓名不能为空',
                'real_name.string' => '真实姓名必须是字符串',
                'real_name.max' => '真实姓名不能超过255个字符',
                'username.required' => '用户名不能为空',
                'username.string' => '用户名必须是字符串',
                'username.max' => '用户名不能超过255个字符',
                'username.unique' => '用户名已存在',
                'password.required' => '密码不能为空',
                'password.string' => '密码必须是字符串',
                'password.min' => '密码不能少于6个字符',
                'password.max' => '密码不能超过255个字符',
                'password.confirmed' => '两次输入的密码不一致',
                'tel.string' => '联系电话必须是字符串',
                'tel.max' => '联系电话不能超过20个字符',
                'memo.string' => '备注必须是字符串',
                'memo.max' => '备注不能超过500个字符',
            ]);

            // 检查用户名是否已存在
            if (WorkUser::where(WorkUser::USERNAME, $validated['username'])->exists()) {
                return $this->failed('用户名已存在', 409);
            }

            // 生成token和过期时间
            $token = md5(uniqid() . time() . $validated['username']);
            $expiredAt = now()->addDays(30); // 30天过期

            // 创建用户
            $workUser = WorkUser::create([
                'real_name' => $validated['real_name'],
                'username' => $validated['username'],
                'password' => Hash::make($validated['password']),
                'tel' => $validated['tel'] ?? null,
                'memo' => $validated['memo'] ?? null,
                'enable' => true,
                'token' => $token,
                'expired_at' => $expiredAt,
            ]);

            return $this->success([
                'token' => $token,
                'expired_at' => $expiredAt->toDateTimeString(),
                'work_user' => new \App\Http\Resources\WorkUserResource($workUser)
            ], '注册成功');

        } catch (ValidationException $e) {
            return $this->failed($e->getMessage());
        } catch (\Exception $e) {
            return $this->error('注册失败');
        }
    }

    /**
     * @OA\Post(
     *     path="/api/work-user/logout",
     *     summary="维护人员登出",
     *     description="清除认证令牌",
     *     tags={"维护人员认证"},
     *     security={{"bearerAuth":{}}},
     *     @OA\Response(
     *         response=200,
     *         description="登出成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="success"),
     *             @OA\Property(property="code", type="integer", example=200),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="登出成功")
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="未授权",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="unauthorized"),
     *             @OA\Property(property="code", type="integer", example=401),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="未登录或登录已失效")
     *         )
     *     ),
     *     @OA\Response(
     *         response=500,
     *         description="服务器错误",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="error"),
     *             @OA\Property(property="code", type="integer", example=500),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="服务器内部错误")
     *         )
     *     )
     * )
     */
    public function logout(Request $request)
    {
        try {
            $workUser = $request->attributes->get('work_user');
            
            if (!$workUser instanceof WorkUser) {
                return $this->unauthorized('未登录或登录已失效');
            }

            // 清除token
            $workUser->token = null;
            $workUser->expired_at = null;
            $workUser->save();

            return $this->success([], '登出成功');

        } catch (\Exception $e) {
            return $this->error('登出失败');
        }
    }

    /**
     * @OA\Get(
     *     path="/api/work-user/profile",
     *     summary="获取维护人员信息",
     *     description="获取当前登录维护人员的详细信息",
     *     tags={"维护人员认证"},
     *     security={{"bearerAuth":{}}},
     *     @OA\Response(
     *         response=200,
     *         description="成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="success"),
     *             @OA\Property(property="code", type="integer", example=200),
     *             @OA\Property(property="data", type="object", ref="#/components/schemas/WorkUserResource"),
     *             @OA\Property(property="message", type="string", example="操作成功")
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="未授权",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="unauthorized"),
     *             @OA\Property(property="code", type="integer", example=401),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="未登录或登录已失效")
     *         )
     *     ),
     *     @OA\Response(
     *         response=500,
     *         description="服务器错误",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="error"),
     *             @OA\Property(property="code", type="integer", example=500),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="服务器内部错误")
     *         )
     *     )
     * )
     */
    public function profile(Request $request)
    {
        try {
            $workUser = $request->attributes->get('work_user');
            
            if (!$workUser instanceof WorkUser) {
                return $this->unauthorized('未登录或登录已失效');
            }

            return $this->success(new \App\Http\Resources\WorkUserResource($workUser));

        } catch (\Exception $e) {
            return $this->error('获取信息失败');
        }
    }
} 